<?php
  /**
   * This class provides helper functions to generate HTML code from an array
   *
   * @author Macdonald Terrence Robinson
   * @package Core
   *
   */
  final class HTML
  {
    public static function generateSelectForObject( $name, $itemsArray, $key, $value, $defaultKey, $multiSelect=false )
    {
      $newArray = array();

      foreach($itemsArray as $row)
        $newArray[$row->$key] = $row->$value;
      
      return self::generateSelect($name, $newArray, $defaultKey, $multiSelect, true);
    }
    
    public static function generateSelect( $name, $itemsArray, $defaultKey, $multiSelect=false, $bypassKeyValueSwitch = false )
    {
      $multi = '';
      
      if($multiSelect)
        $multi = ' multiple size="5"';
      
      $select = '<select name="'.$name.'"'.$multi.' id="'.$name.'">';
      foreach ($itemsArray as $key=>$value)
      {
        if( is_numeric($key) )
          if(!$bypassKeyValueSwitch)
            $key = $value;
        
        if( $defaultKey === $key )
          $select.= '<option value="'.$key.'" selected="selected">'.$value.'</option>';
        else
          $select.= '<option value="'.$key.'">'.$value.'</option>';
      }
      $select .= '</select>';
      
      return $select;
    }
    
    public static function generateList($listArray, $tag = 'ul', $id='', $spacer = '', $addToEndOnEachLI = '')
    {
      $ulAttrsString = '';
      
      if($id !='')
        $ulAttrsString = " id='$id'";
      
      $html = "<$tag$ulAttrsString>";
      foreach ($listArray as $key=>$value)
      {
        $attrString = '';

        foreach ($listArray[$key]['attributes'] as $attrName=>$attrValue)
          $attrString .=" $attrName = '$attrValue'";

        if( Utility::isLastIndex($value, $listArray) )
          $spacer = '';

        $html .= "<li><a$attrString>".$listArray[$key]['value']."</a>$addToEndOnEachLI$spacer</li>";

      }
      $html .= "</$tag>";
      
      return $html;
    }

    public static function mergeLists( array $lists, $tag = 'ul', $id='', $spacer = '' )
    {
      $mergedList = "<$tag id='$id'>";

      foreach ($lists as $key=>$value)
      {
        if( !Utility::isLastIndex($value, $lists) )
          $value = str_replace('</li>', "$spacer</li>", $value);

        $mergedList .= str_replace(array('<ul>','</ul>','<ol>','</ol>'), '', $value);
      }

      $mergedList .= "</$tag>";

      return $mergedList;
    }
  }
?>
